#include "UIManager.h"

UIManager::UIManager(){
    _count = 0; //init without a canvas
    _currentindx = 0;
}

void UIManager::run(){
    _handleCtrl();
    if (_count > 0){
        cavs[_currentindx]->draw();
    }
}

void UIManager::_handleCtrl(){
    OSL_CONTROLLER *ctrl = oslReadKeys();
    oslCls();
    if(_count > 0){

            cavs[_currentindx]->handlectrl(ctrl);

        if(osl_keys->pressed.L){
            SwithToCanv(-1);
        }
        if(osl_keys->pressed.R){
            SwithToCanv(1);
        }
    }
}

void UIManager::SwithToCanv(int inx){
    cavs[_currentindx]->onblur();
  _currentindx = (_currentindx + inx + _count) % _count;
  cavs[_currentindx]->onhover();
}

void UIManager::AddCanvas(Canvas* canvas){
  cavs[_count++] = canvas;
  canvas->pagenum = _count;
  canvas->totalpagenum = &_count;
}

void UIManager::unload(){
    oslEndGfx();
    oslQuit();
    curl_global_cleanup();
}

UIManager::~UIManager(){
}

void UIManager::load(){
    //set old school lib parameters
    oslInit(0);
    oslInitGfx(OSL_PF_8888, 1);
    oslInitAudio();
    oslSetDrawBuffer(OSL_SECONDARY_BUFFER);
    oslSetQuitOnLoadFailure(1);
    oslSetKeyAutorepeatInit(40);
    oslSetKeyAutorepeatInterval(10);
    oslIntraFontInit(INTRAFONT_CACHE_ALL | INTRAFONT_STRING_UTF8);
}

bool UIManager::ParseDoc(TiXmlDocument* doc){
     if(doc && doc->FirstChildElement()){
        TiXmlElement* node = doc->FirstChildElement()->FirstChildElement("Item");
        genUI(node);

        TiXmlElement* child = node->NextSiblingElement("Item");
        while(child){
          genUI(child);
          child = child->NextSiblingElement("Item");
        }

        return true;
     }
     return false;
}


bool UIManager::genUI(TiXmlElement* ele){
    Canvas* can = new Canvas();
    AddCanvas(can);
    TiXmlElement* button = ele->FirstChildElement("button");
    Button *btn = new Button(10,PSP_SCREEN_HEIGHT-30,50,25,*(button->Attribute("down")));
    btn->downloadable = true;
    TiXmlElement* file = ele->FirstChildElement("file");

    Button *btn1 = new Button(80,PSP_SCREEN_HEIGHT-30,50,25,*(button->Attribute("run")));
    btn1->runnable = true;

    TiXmlElement* photo = ele->FirstChildElement("photo");
    Image *img1;
    if(photo){
      Peer pe(*(photo->Attribute("url")),*(photo->Attribute("name")));
      pe.runsingle();
      img1 = new Image(5,5,*(photo->Attribute("name")));
    }else
      img1 = new Image(5,5,"green.png");

    Info *inf = new Info(220,5,PSP_SCREEN_WIDTH-230,PSP_SCREEN_HEIGHT-50);

    struct titles mytitle = {
     *(ele->Attribute("name")),
     *(ele->Attribute("producer")),
     *(ele->Attribute("date")),
     *(ele->Attribute("language")),
     *(ele->Attribute("size")),
     *(ele->Attribute("category")),
      5,
      20,
      *(ele->Attribute("description"))};

    inf->setTitles(mytitle);
    can->AddComponent(img1);
    can->AddComponent(btn);
    can->AddComponent(btn1);
    can->AddComponent(inf);
    return true;
}
